/****************************************************
          File Name:socket_server.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Thu 25 Sep 2014 07:49:22 PM CST
*****************************************************/

#include"net.h"

int main(int argc,char *argv[])
{
    int sfd, acfd,bytes;
    struct sockaddr_un addr;
    char *buf;

    buf=malloc(SIZE);
    remove(path);

    sfd=socket(AF_UNIX,SOCK_STREAM,0);      /* 1 */
    if(sfd==-1)
        err("socket");
    if(memset(&addr,0,sizeof(struct sockaddr_un))==NULL)
        err("set addr to null failed");

    addr.sun_family=AF_UNIX;                                /* 2 */
    if(strncpy(addr.sun_path,path,sizeof(path)-1)==NULL)    /* 2 */
        err("set addr.sun_path");

    if(bind(sfd,(struct sockaddr *)&addr,sizeof(struct sockaddr_un))==-1) /* 3 */
        err("bind");
    if(listen(sfd,5)==-1)       /* 4 */
        err("listen");

    for(;;)
    {
        acfd=accept(sfd,NULL,NULL);     /* 5 */
        if(acfd==-1)
            err("accept");
        while((bytes=read(acfd,buf,SIZE))>0)
            if(write(STDOUT_FILENO,buf,bytes)!=bytes)
                err("write");
        if(bytes==-1)
                err("read");
        if(close(acfd)==-1)
            err("close");
    }
    return 0;
}
